<script setup>
import { reactive, ref } from 'vue'
import { onLoad } from "@dcloudio/uni-app";
import SelectPopup from "@/components/selectPopup.vue";
import SelectPark from "@/components/selectPark.vue";
import DatePopup from "@/components/datePopup.vue";
import { baseUrl, host } from "@/utils/config";
import { uploadUrl } from "@/api";
import Uploader from "@/components/uploader.vue";
import { getdeptByparentid,getaqjcGcomptype, getParkCompanyDetail, addaqjcGardenCompanyInfo, modifyaqjcGardenCompanyInfo } from "@/api/park";

onLoad(async (e) => {
  if(e.id){
    loading.value = true
    getParkCompanyDetail(e.id).then(res => {
        pageData.formData = res.data
        deptName.value = pageData.formData.deptName
       /*  if(pageData.formData.lon && pageData.formData.lat){
          position.value = pageData.formData.lon + ' ' + pageData.formData.lat
        } */
        pageData.formData.compImage = pageData.formData.compImage ? [{url:host+pageData.formData.compImage}] :''
        pageData.formData.compTypeIds = pageData.formData.compTypeIds ? pageData.formData.compTypeIds.map(str => parseInt(str)) : []
        loading.value = false
    })
  }else{
    deptName.value = userInfo.dept.deptName
    pageData.formData.deptId = userInfo.dept.deptId
    pageData.formData.deptName = userInfo.dept.deptName
  }
  getcomptype()
})
const getLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: function (res) {
      pageData.formData.lon = res.longitude
      pageData.formData.lat = res.latitude
      // position.value = res.longitude + ' ' + res.latitude
    },
    fail: function (err) {
      console.log('errrrrr', err)
    }
  })
}
const loading = ref(false)
const userInfo = uni.getStorageSync('userInfo')
const dict = reactive({})
const formData = ref(null)
const pageData = reactive({
  formData: {
    deptId: null,
    compName: null,
    compScale: null,
    compType: null,
    compTypeIds: [],
    compCode: null,
    compImage: [],
    compNum: null,
    compAddress: null,
    compPerson: null,
    gardenPhone: null,
    safePerson: null,
    safePhone: null,
    lon: null,
    lat: null,
    remark: null,
  },
  aqjcGcomptypeData: []
})
const position = ref(null)
const deptName = ref(null)
const pathChange = (e) => {
  deptName.value = e.map(item => item.text).toString()
  pageData.formData.deptId = e[e.length-1].value
  pageData.formData.deptName = e[e.length-1].text
}
const formRule = {
  compName: [
    {
      required: true,
      message: '请输入企业名称'
    }
  ] 
}
const loadingBtn = ref(false)
/* 涉及风险种类下拉 */
const getcomptype = async() => {
  await getaqjcGcomptype({}).then(res => {
    pageData.aqjcGcomptypeData = res.data
  })
}

Object.assign(dict, uni.getStorageSync('dict'))
const save = () => {
  uni.setStorage({
    key: 'createParkCatch',
    data: pageData.formData,
    success: () => {
      uni.showToast({
        title: '暂存成功！',
        icon: 'success'
      })
    }
  })
}
const submit = () => {
  // console.log('pageData.formData', pageData.formData)
  formData.value.validate().then(({ valid, errors }) => {
    if (valid) {
      if(pageData.formData.deptId === null){
        uni.showToast({
          icon: 'none',
          title: "请选择所属园区"
        })
        return false;
      }
      const reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/;
      if(pageData.formData.gardenPhone){
        if(!reg.test(pageData.formData.gardenPhone)){
          uni.showToast({
            icon: 'none',
            title: "请填写正确的负责人联系方式"
          })
          return false;
        }
      }
      if(pageData.formData.safePhone){
        if(!reg.test(pageData.formData.safePhone)){
          uni.showToast({
            icon: 'none',
            title: "请填写正确的安全人员联系方式"
          })
          return false;
        }
      }
      if(pageData.formData.compImage.length>0){
        let imgUrl = pageData.formData.compImage[0].url.replace(new RegExp(`\\b${host}\\b`, 'i'), '');
        pageData.formData.compImage = imgUrl
        // console.log('imgUrl', imgUrl)
      }else{
        pageData.formData.compImage = ''
      }
      console.log('提交pagedata', pageData.formData)
      // return
      loadingBtn.value = true
      let api
      let msg = ''
      if (pageData.formData.id) {
        api = modifyaqjcGardenCompanyInfo
        msg = '更新成功！'
      } else {
        api = addaqjcGardenCompanyInfo
        msg = '新增成功！'
      }
      api(pageData.formData).then(res => {
        console.log('create', res)
        uni.showToast({
          title: msg
        })
        uni.navigateBack()
      }).catch(err => {
        loadingBtn.value = false
      })
    }
    else {
      console.log('error submit!!', errors)
      uni.showToast({
        title: errors[0].message,
        icon: 'none'
      })
    }
  })
}
</script>

<template>
    <nut-loading-page :loading="loading" />
    <nut-form :model-value="pageData.formData" ref="formData" :rules="formRule" label-width="100">
        <!-- <nut-form-item label="所属园区" prop="deptId"> -->
          <select-park class="selectPark" @pathChange="pathChange" :modelName="deptName" v-model="pageData.formData.deptId"></select-park>
        <!-- </nut-form-item> -->
        <nut-form-item label="企业名称" prop="compName">
            <nut-input v-model="pageData.formData.compName" placeholder="请输入企业名称" />
        </nut-form-item>
        <nut-form-item label="企业规模" prop="compScale">
            <select-popup v-model="pageData.formData.compScale" :echo="pageData.formData.dictLabel" :columns="dict.sys_comp_scale"></select-popup>
        </nut-form-item>
        <nut-form-item label="企业类型" prop="compType">
            <select-popup v-model="pageData.formData.compType" :echo="pageData.formData.dictLabel" :columns="dict.sys_comp_type"></select-popup>
        </nut-form-item>
        <nut-form-item label="涉及风险种类" prop="compTypeIds">
          <nut-checkboxgroup v-model="pageData.formData.compTypeIds">
            <nut-checkbox v-for="(item,index) in pageData.aqjcGcomptypeData" :key="item.typeId" :label="item.typeId">{{item.typeName}}</nut-checkbox>
          </nut-checkboxgroup>
        </nut-form-item>
        <nut-form-item label="统一信用编码" prop="compCode">
            <nut-input v-model="pageData.formData.compCode" placeholder="请输入统一信用编码" />
        </nut-form-item>
        <nut-form-item label="企业图片" prop="compImage">
            <uploader v-model="pageData.formData.compImage" :url="uploadUrl" return-type="object" :limit="1"></uploader>
        </nut-form-item>
        <nut-form-item label="企业人数" prop="compNum">
            <nut-input-number v-model="pageData.formData.compNum" input-width="100" min="1" />
        </nut-form-item>
        <nut-form-item label="地址" prop="compAddress">
            <nut-input v-model="pageData.formData.compAddress" placeholder="请输入地址" />
        </nut-form-item>
        <nut-form-item label="负责人" prop="compPerson">
            <nut-input v-model="pageData.formData.compPerson" placeholder="请输入负责人" />
        </nut-form-item>
        <nut-form-item label="联系方式" prop="gardenPhone">
            <nut-input v-model="pageData.formData.gardenPhone" placeholder="请输入联系方式" />
        </nut-form-item>
        <nut-form-item label="安全人员" prop="safePerson">
            <nut-input v-model="pageData.formData.safePerson" placeholder="请输入安全人员" />
        </nut-form-item>
        <nut-form-item label="联系方式" prop="safePhone">
            <nut-input v-model="pageData.formData.safePhone" placeholder="请输入联系方式" />
        </nut-form-item>
        <view class="position">
          <nut-form-item label="经度和纬度" prop="position">
            <nut-input v-model="pageData.formData.lon" placeholder="经度" />
            <nut-input v-model="pageData.formData.lat" placeholder="纬度" />
          </nut-form-item>
          <nut-button size="mini" type="primary" @click="getLocation">获取位置</nut-button>
        </view>
        <nut-form-item label="备注" prop="remark">
            <nut-input v-model="pageData.formData.remark" placeholder="请输入备注" />
        </nut-form-item>
    </nut-form>
  <nut-cell>
    <nut-row :gutter="20">
      <nut-col :span="12">
        <nut-button :loading="loadingBtn" type="success" block @click="submit">提交</nut-button>
      </nut-col>
      <nut-col :span="12">
        <nut-button :loading="loadingBtn" type="default" block @click="save">暂存</nut-button>
      </nut-col>
    </nut-row>
  </nut-cell>
       
</template>

<style scoped lang="scss">
</style>
<style lang="scss">
.position{
  position: relative;
}
.position .nut-button{
  position: absolute;
  right: 20px;
  top: 50%;
  margin-top: -12px;
  z-index: 99;
}
.selectPark{
  padding: 0;
  .nut-cell__value{
    flex: 2;
  }
}
</style>